package com.yaorange.springsecuirtydemo.service;

import com.yaorange.springsecuirtydemo.domain.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author coach tam
 * @email 327395128@qq.com
 * @values 坚持灵活 灵活坚持
 * @since 2024/5/28
 */
@Component
public class TokenService {
    //模拟存储到redis
    //token -> authentication
    public static Map<String, Authentication> tokenMap = new ConcurrentHashMap<>();

    //保存令牌
    public void saveToken(String token, Authentication authentication) {
        tokenMap.put(token, authentication);
    }

    //获取登录认证信息
    public LoginUser getLoginUser(HttpServletRequest request) {
        String token = request.getParameter("token");
        Authentication authentication = tokenMap.get(token);
        if (authentication == null) {
           throw new RuntimeException("token is invalid");
        }
        return (LoginUser) authentication.getPrincipal();
    }
}
